package com.smartstate.EnvironmentMonitor.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartstate.EnvironmentMonitor.dto.DataDTO;
import com.smartstate.EnvironmentMonitor.dto.PageDTO;
import com.smartstate.EnvironmentMonitor.entity.EquipMent;
import com.smartstate.EnvironmentMonitor.mapper.DataMapper;
import com.smartstate.EnvironmentMonitor.service.DataService;
import com.smartstate.EnvironmentMonitor.vo.DataVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
@Slf4j
public class DataServiceImpl extends ServiceImpl<DataMapper, EquipMent> implements DataService{

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public List<DataVO> getRealTime(DataDTO dataDTO, List<DataVO> list) {
        if(dataDTO == null){
            return list;
        }
        Map<String, List<String>> map = dataDTO.getMap();
        for (String deviceId : map.keySet()) {
            for (String attribute : map.get(deviceId)) {
                if (list.size() < 8){
//                    获取属性状态，判断是添加到list还是从list删除该属性
                    String status = StringUtils.substringAfter(attribute, "-");
                    attribute = StringUtils.substringBefore(attribute, "-");
                    if ("1".equals(status)){
                        DataVO dataVO = new DataVO();
                        String attributeValue = (String) redisTemplate.opsForHash().get(deviceId, attribute);
                        dataVO.setId(deviceId);
                        dataVO.setAttribute(attribute);
                        dataVO.setCurrentValue(attributeValue);
                        list.add(dataVO);
                    } else {
                        for(DataVO dVO : list){
                            if (dVO.getAttribute().equals(attribute) && dVO.getId().equals(deviceId)) {
                                list.remove(dVO);
                                break;
                            }
                        }
                    }
                }else {
                    return list;
                }
            }
        }
        return list;
    }

    @Override
    public Page<EquipMent> queryAllPageByDTO(PageDTO pageDTO) {
        return null;
    }
}
